package pyip.lib.javalearn.thread.lock.waitnotify;

import pyip.lib.javalearn.Printer;

/**
 * wait(timeout) 在两种情况下会被唤醒, 1) notify, 2) 超时且监听器不被其他线程占用。<br>
 * @author yepeng
 * @date 2015年5月15日
 */
public class WaitTimeoutDemo implements Runnable {

    @Override
    public void run() {
        Printer.out.println("t1 start", 1);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (this) {
            Printer.out.println("t1 enter sync", 1);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Printer.out.println("t1 leave sync", 1);
            // 对于wait(timeout) 不需要notify也是可以的
            // notify();
        }
    }

    public static void main(String[] args) {
        Printer.out.println("main start", 0);
        WaitTimeoutDemo r1 = new WaitTimeoutDemo();
        Thread t1 = new Thread(r1);
        t1.start();
        synchronized (r1) {
            try {
                Printer.out.println("main enter sync", 0);
                Printer.out.println("main wait", 0);
                r1.wait(3000);
                // r1.wait();
                Printer.out.println("main wakeup", 0);
                Thread.sleep(5000);
                Printer.out.println("main leave sync", 0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
